###############################################################################
#
#  	    File        : Makefile
#
#       Abstract    : Example Makefile for STM32 C Project
#
#       Environment : Atollic TrueSTUDIO(R)
#
###############################################################################

# System configuration
CC = arm-atollic-eabi-gcc
RM=rm -rf

# Assembler, Compiler and Linker flags and linker script settings
LINKER_FLAGS=-mthumb -mcpu=cortex-m3 -Wl,--gc-sections -T$(LINK_SCRIPT) -static  -Wl,-cref "-Wl,-Map=$(BIN_DIR)/Termometr.map"
LINK_SCRIPT="stm32_flash.ld"
ASSEMBLER_FLAGS=-c -g -O2 -mcpu=cortex-m3 -mthumb  -x assembler-with-cpp
COMPILER_FLAGS=-c -g -mcpu=cortex-m3 -O2 -Wall -ffunction-sections -fdata-sections -mthumb -D"STM32F10X_MD_VL" -D"USE_STDPERIPH_DRIVER"   -Isrc -ILibraries\STM32F10x_StdPeriph_Driver\inc -ILibraries\CMSIS\CM3\CoreSupport -ILibraries\CMSIS\CM3\DeviceSupport\ST\STM32F10x 

# Define output directory
OBJECT_DIR = Debug
BIN_DIR = $(OBJECT_DIR)

# Define sources and objects
SRCS := $(wildcard src/*.c)
OBJS := $(SRCS:%.c=$(OBJECT_DIR)/%.o)  
LIBSRCS := $(wildcard Libraries/*/*/*/*.c) \
	$(wildcard Libraries/*/*/*/*/*/*.c) \
	$(wildcard Libraries/*/*/*.c) \
	$(wildcard Utilities/STM32_EVAL/*/*.c) \
	$(wildcard hal/*/*/*/*.c ) \
	$(wildcard hal/*/*/*.c ) \
	$(wildcard hal/*/*.c ) \
	$(wildcard hal/*.c )
LIBSRCSASM := 	$(wildcard Libraries/*/*/*/*/*/*/*/*.s)
LIBSRCASM  :=	$(wildcard hal/*/*/*.S )  
LIBOBJS := $(LIBSRCS:%.c=$(OBJECT_DIR)/%.o) $(LIBSRCSASM:%.s=$(OBJECT_DIR)/%.o) $(LIBSRCASM:%.S=$(OBJECT_DIR)/%.o)

###############
# Build project
# Major targets
###############
all: buildelf
	arm-atollic-eabi-size $(BIN_DIR)/Termometr.elf

lib: $(LIBOBJS)	

buildelf: lib $(OBJS) 
	$(CC) -o "$(BIN_DIR)/Termometr.elf" $(OBJS) $(LIBOBJS) $(LINKER_FLAGS)

clean:
	$(RM) $(OBJS) $(LIBOBJS) "$(BIN_DIR)/Termometr.elf" "$(BIN_DIR)/Termometr.map"


##################
# Specific targets
##################
$(OBJECT_DIR)/src/main.o: src/main.c
	@mkdir $(subst /,\,$(dir $@)) 2> NUL || echo off
	$(CC) $(COMPILER_FLAGS) src/main.c -o $(OBJECT_DIR)/src/main.o 

$(OBJECT_DIR)/src/stm32f10x_it.o: src/stm32f10x_it.c
	@mkdir $(subst /,\,$(dir $@)) 2> NUL || echo off
	$(CC) $(COMPILER_FLAGS) src/stm32f10x_it.c -o $(OBJECT_DIR)/src/stm32f10x_it.o 


##################
# Implicit targets
##################
$(OBJECT_DIR)/%.o: %.c
	@mkdir $(subst /,\,$(dir $@)) 2> NUL || echo off
	$(CC) $(COMPILER_FLAGS) $< -o $@

$(OBJECT_DIR)/%.o: %.s
	@mkdir $(subst /,\,$(dir $@)) 2> NUL || echo off
	$(CC) $(ASSEMBLER_FLAGS) $< -o $@
